var express = require('express');
var router = express.Router();
var db = require("../util/DataBase.js")

var articleService = require("../service/article.js");
var topicService = require("../service/topic.js");
var messageService = require("../service/message.js");
var searchService = require("../service/search.js");

router.post('/create', function(req, res, next) {
  var body = req.body;

  var values = [
    body.title,
    body.content,
    body.question ? 1 : 0,
    new Date(),
    req.session.user.id,
    0
  ];

  db.query("INSERT INTO `article` (`title`, `content`, `question`, `create_datetime`, `user_id`, `rank`) VALUES (?, ?, ?, ?, ?, ?)", values, function(err, results) {
      if(err)
      {
        res.json(null, -1, "创建帖子失败")
      }
      else
      {
        res.json({
          id: results.insertId
        });
      }

  });

});

router.post('/set_topic/:articleId', function(req, res, next) {

  var body = req.body;

  var topicIdList = body.topicIdList;
  var articleId = req.params.articleId;

  var insertNum = topicIdList.length;

  var insertComplete = 0;

  articleService.isQuestion(articleId, function (result) {
    if(result) {
      for(var i = 0; i < insertNum; ++ i) {
        messageService.fire("question", topicIdList[i] + "_" + articleId);
      }
    }
  });

  var values = [
    articleId,
    req.session.user.id,
  ];

  db.query("UPDATE `article` SET `draft` = 0 WHERE `id` = ? AND `draft` = 1 AND `user_id` = ?", values, function(err, results) {
      if(err)
      {
        res.json(null, -1, "更新草稿失败")
      }
      else
      {

        articleService.removeAllTopic(articleId, () => {

          for(var i = 0; i < insertNum; ++ i)
          {

            let values = [
              articleId,
              topicIdList[i]
            ];

            db.query(
              "SELECT max(`publish_id`) as `max_publish_id` FROM article",
              [
                articleId
              ],
              function (err, results) {
                if(err) {
                  res.json(null, -1, "获取max_publish_id失败");
                } else {

                  var maxPublishId = results[0].max_publish_id;
                  if(maxPublishId == null) {
                    maxPublishId = 1;
                  } else {
                    ++ maxPublishId;
                  }

                  db.query(
                    "UPDATE article SET `publish_id` = ? WHERE `id` = ?",
                    [
                      maxPublishId,
                      articleId
                    ],
                    function (err, results) {
                      if(err) {
                        res.json(null, -1, "设置publish_id失败");
                      }
                    }
                  )

                }
              }
            )

            db.query("INSERT INTO `article_in_topic` (`article_id`, `topic_id`) VALUES (?, ?)", values, function(err, results) {

              if(err)
              {
                res.json(null, -1, "设置帖子主题失败")
              }
              else
              {
                if(++ insertComplete == insertNum)
                {
                  searchService.addArticle(articleId);
                  res.json(null);
                }
              }

            });
          }

        }, () => {
          res.json(null, -2, "删除帖子原有主题失败")
        });

      }

  });


});

router.get('/:id', function(req, res, next) {

  var values = [
    req.params.id
  ]

  db.query("SELECT `id`, `title`, `content`, `question`, `create_datetime`, `user_id` FROM `article` WHERE `id` = ?", values, function(err, results) {

      if(err)
      {
          res.json(null, -1, "获取帖子数据失败")
          return;
      }
      if(results.length > 0)
      {

          results[0].question = results[0].question == 1;
          results[0].create_datetime = results[0].create_datetime.getTime();

          db.query("SELECT `id`, `nickname`, `avatar_url` FROM `user` WHERE `id` = ?", [results[0].user_id], function (err, userResults) {
            results[0].user = userResults[0];
            res.json(results[0])
          });
      }
      else
      {
        res.json(null, 1, "不存在此帖子")
      }

  });

});

router.get('/list/:topicId', function(req, res, next) {
  topicService.getArticleList(req.session.user.id, req.params.topicId, req.query.len, req.query.startPublishId, req.query.sort, req.query.knowledge, (articleInTopicList) => {

    if(articleInTopicList.length <= 0)
    {
      res.json([]);
      return;
    }

    var idList = [];

    for(var i = 0, l = articleInTopicList.length; i < l; ++ i)
    {
      idList.push(parseInt(articleInTopicList[i].article_id));
    }

    db.query("SELECT `id`, `title`, `content`, `question`, `knowledge`, `user_id`, `create_datetime`, `publish_id` FROM `article` WHERE `id` IN (" + idList.join(",") + ") ORDER BY `publish_id` DESC", function(err, results) {

        if(err)
        {
          res.json(null, -1, "查询帖子失败");
          return;
        }

        if(results.length <= 0) {
          res.json([]);
          return;
        }

        var userLoaded = 0;

        for(var i = 0, l = results.length; i < l; ++ i) {
          var article = results[i];
          (function (_article) {
            _article.create_datetime_st = _article.create_datetime.getTime();
            db.query("SELECT `id`, `nickname`, `avatar_url` FROM `user` WHERE `id` = ?", [_article.user_id], function (err, userResults) {
              _article.user = userResults[0];
              if(++ userLoaded == l) {
                res.json(results);
              }
            });
          })(article);
        }

    });

  }, () => {
    res.json(null, -1, "获取主题关联帖子失败");
  })

});

router.get('/author/:id', function(req, res, next) {

  var values = [
    req.params.id * 1,
    req.query.startPublishId * 1,
    req.query.len * 1
  ];

  db.query("SELECT `id`, `title`, `content`, `question`, `publish_id`, `user_id`, `create_datetime`, `update_datetime` FROM `article` WHERE `user_id` = ? AND `draft` = 0 AND `publish_id` IS NOT NULL AND `publish_id` " + ( req.query.dir === "down" ? "<" : ">") + " ? ORDER BY `publish_id` DESC LIMIT ?", values, function(err, results) {

      if(err)
      {
        res.json([], -1, "查询帖子失败");
        return;
      }

      if(results.length <= 0) {
        res.json([]);
        return;
      }

      var userLoaded = 0;

      for(var i = 0, l = results.length; i < l; ++ i) {
        var article = results[i];
        (function (_article) {
          _article.create_datetime_st = _article.create_datetime.getTime();
          _article.update_datetime_st = _article.update_datetime.getTime();
          db.query("SELECT `id`, `nickname`, `avatar_url` FROM `user` WHERE `id` = ?", [_article.user_id], function (err, userResults) {
            _article.user = userResults[0];
            if(++ userLoaded == l) {
              res.json(results);
            }
          });
        })(article);
      }

  });

});

router.post('/create_draft', function(req, res, next) {
  var body = req.body;

  var values = [
    body.title || "",
    body.content || "[]",
    body.question ? 1 : 0,
    body.knowledge ? 1 : 0,
    new Date(),
    req.session.user.id,
    0,
    1,
    new Date()
  ];

  db.query("INSERT INTO `article` (`title`, `content`, `question`, `knowledge`, `create_datetime`, `user_id`, `rank`, `draft`, `update_datetime`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)", values, function(err, results) {
      if(err)
      {
        res.json(null, -1, "创建草稿失败")
      }
      else
      {
        res.json({
          id: results.insertId
        });
      }

  });

});

router.post('/update_draft/:id', function(req, res, next) {

  var body = req.body;

  var values = [
    body.title || "",
    body.content || "[]",
    body.question ? 1 : 0,
    body.knowledge ? 1 : 0,
    0,
    new Date(),
    body.draft == 0 ? 0 : 1,
    req.params.id * 1,
    req.session.user.id,
  ];

  db.query("UPDATE `article` SET `title` = ?, `content` = ?, `question` = ?, `knowledge` = ?, `rank` = ?, `update_datetime` = ?, `draft` = ? WHERE `id` = ? AND `draft` = 1 AND `user_id` = ?", values, function(err, results) {
      if(err)
      {
        res.json(null, -1, "更新草稿失败")
      }
      else
      {
        res.json();
      }

  });

});

router.post('/publish/:id', function(req, res, next) {
  var body = req.body;

  var values = [
    req.params.id * 1,
    req.session.user.id
  ];

  db.query("UPDATE `article` SET `draft` = 0 WHERE `id` = ? AND `user_id` = ?", values, function(err, results) {
      if(err)
      {
        res.json(null, -1, "发布帖子失败")
      }
      else
      {
        res.json();
      }

  });

});

router.get('/draft/:type', function(req, res, next) {

  var values = [
    req.session.user.id,
    req.params.type == "question" ? 1 : 0,
    req.params.type == "knowledge" ? 1 : 0,
  ]

  db.query("SELECT `id`, `title`, `content`, `question`, `update_datetime` FROM `article` WHERE `user_id` = ? AND `draft` = 1 AND `question` = ? AND `knowledge` = ? ORDER BY `id` DESC LIMIT 10", values, function(err, results) {

      if(err)
      {
          res.json(null, -1, "获取帖子数据失败")
          return;
      }
      else
      {
        if(results.length <= 0) {
          res.json([]);
        } else {
          results.forEach((article) => {
            article.update_datetime_st = article.update_datetime.getTime();
          });
          res.json(results);
        }
      }

  });

});

module.exports = router;
